package rpc.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Optional;
import jodd.io.FileUtil;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtils {

  private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

  public static <T> Optional<T> read(String filePath, Class<T> t, boolean delOverRead) {

    Optional<T> optional = Optional.empty();
    try {
      if (!new File(filePath).exists()) {
        return optional;
      }

      File file = new File(filePath);
      try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file))) {
        optional.orElse((T) inputStream.readObject());
      }
      if (delOverRead) {
        FileUtil.delete(file);
      }
    } catch (Exception e) {
      logger.error("exception:{} stackTrace:{}", e.getMessage(), ExceptionUtils.getTrace(e));
      logger.error("load file:{},error:{}", filePath, e.getMessage());
    }
    return optional;
  }

  public static void write(String filePath, Object obj) {
    try {
      String fullPath = FilenameUtils.getFullPath(filePath);
      File f = new File(fullPath);
      if (!f.exists()) {
        f.mkdirs();
      }
      f = new File(filePath);
      if (!f.exists()) {
        f.createNewFile();
      }
    } catch (Exception e) {
      logger.error("write 1 file:{},error:{}", filePath, e.getMessage());
    }
    try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(filePath)))) {
      objectOutputStream.writeObject(obj);
    } catch (IOException e) {
      logger.error("write 2 file:{},error:{}", filePath, e.getMessage());
    }
  }
}
